package Lock_2;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class BankAccount {
    private int balance = 1000;
    private final Lock lock = new ReentrantLock();

    public void deposit(int amount) {
        lock.lock();
        try {
            int temp = balance + amount;
            Thread.sleep(10); // 模拟处理延迟
            balance = temp;
            System.out.println(Thread.currentThread().getName() + " 存入 " + amount + ", 余额: " + balance);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void withdraw(int amount) {
        lock.lock();
        try {
            if (balance >= amount) {
                int temp = balance - amount;
                Thread.sleep(10); // 模拟处理延迟
                balance = temp;
                System.out.println(Thread.currentThread().getName() + " 取出 " + amount + ", 余额: " + balance);
            } else {
                System.out.println(Thread.currentThread().getName() + " 余额不足");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class 基本Lock使用 {
    public static void main(String[] args) {
        final BankAccount account = new BankAccount();

        // 创建20个存款线程
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                public void run() {
                    account.deposit(100);
                }
            }, "存款线程-" + i).start();
        }

        // 创建20个取款线程
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                public void run() {
                    account.withdraw(100);
                }
            }, "取款线程-" + i).start();
        }
    }
}